<style>
#jGridForOrderArrangements .panelBar {border-top-width: 0px;}
.ui-sortable > li {margin: 5px 0px; height: 22px; line-height: 20px; text-indent: 3px; cursor: default; position: relative;}
.ui-sortable > li > div {float: left; height: 20px; cursor: default;}
#jGridForOrderArrangements tbody>tr {border-bottom: 1px solid #E5EDF3; border-bottom-style: double; padding: 5px 0px;}
#jGridForOrderArrangements tbody td > .gridCol {padding: 0px;}
.ui-sortable > li > .order-depict {border: 1px solid #DBE3EA;}
.ui-sortable > li > .order-depict:hover {border: 1px solid #586C79;}
.order, .orderPlan {position: relative;}
.orderPlan {float: left; margin-right: 1px; min-width: 8px; height: 20px !important;}
.drop-hovered {background: #ECF5EA;}
#jGridForOrderArrangements .ui-draggable-dragging{height: 21px;};
.orderPlanRemove{opacity: 0.8};
#jGridForOrderArrangements .right-border {border-right-color: black;}
#jGridForOrderArrangements .bottom-border {border-bottom-color: #DBE0E3;}
#jGridForOrderArrangements th, #jGridForOrderArrangements td {
    border-color: #F4F4F4;
    padding-top: 4px;
    padding-bottom: 4px;
}
#jGridForOrderArrangements .order, 
#jGridForOrderArrangements .order-depict, 
#jGridForOrderArrangements .orderPlan {background: url("${rc.getContextPath()}/manage/styles/basicColor/basicColor.png") repeat-x;}
#PrductionOrderPlanEdit_dialog dl {position: relative !important;}
#PrductionOrderPlanEdit_dialog dd > span.error {position: static !important; float: right !important; margin-left: 1px;}
.unarrangedOrder {background: white !important; width: 100%; height: 20px !important; float: right !important;}
.standard, .actual {text-align: center; color: #666 !important;}
.actual > span {display: inline-block; height: 21px; line-height: 21px;}
.greatThanStandard {color: #FE2703 !important;}
.lessThanStandard {color: #00BC00 !important;}
.orderNumSpan {position: absolute; height: 20px; line-height: 20px;}
.order-icon {float: left !important; width: 20px !important; height: 22px !important; position: absolute !important; background-color: white;}
.order-icon.status1 {background: white;}
.order-icon.status2 {background-position: -473px -846px;}
.order-icon.status3, .order-icon.status4 {background-position:  2px -1184px;}
.order-depict {float: left !important; height: 20px !important; position: absolute !important; left: 20px; right: 0px;}
.gridScrollerBar .order-depict {width: 120px;}
</style>
<link href="${rc.getContextPath()}/manage/styles/jquery-ui/jquery-ui.min.css?v=${ver}" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${rc.getContextPath()}/manage/js/jquery-ui.min.js"></script>
<div class="pageContent" id="jGridForOrderArrangements" style="min-width: 1000px;"></div>
<!-- 订单信息弹出层内容 -->
<div id="arrangeOrderWorkCenter" class="pageFormContent" style="display: none;">
    <fieldset>
        <dl>
            <dt><@label key="orderFormNum.C,colon">订单编号：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="orderStatus.C,colon">订单状态：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="materialCode.C,colon">物料编号：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="materialText.C,colon">物料描述：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="orderQuantity.C,colon">订单数量：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="workCenter.C,colon">工作中心</@label></dt>
            <dd>
                <select name="workCenterCode" disabled="disabled"></select>
            </dd>
        </dl>
        <dl>
            <dt><@label key="plannedstartDateTime.C,colon">计划开始时间：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput date" type="text">
                <a class="inputDateButton" href="javascript:;"></a>
            </dd>
        </dl>
        <dl>
            <dt><@label key="plannedendDateTime.C,colon">计划结束时间：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput date" type="text">
                <a class="inputDateButton" href="javascript:;"></a>
            </dd>
        </dl>
    </fieldset>
    <ul style="float: right; margin: 10px 13px 0px 0px;">
        <li style="float: right; margin-left: 10px;">
            <div class="buttonActiveGrey">
                <div class="buttonContent">
                    <button type="button" class="close"><@label key="cancel.B">取消</@label></button>
                </div>
            </div>
        </li>
        <li style="float: right;">
            <div class="buttonActive">
                <div class="buttonContent">
                    <button type="button" class="submit"><@label key="ok.B">确定</@label></button>
                </div>
            </div>
        </li>
    </ul>
</div>
<!-- 订单信息弹出层内容 -->
<div id="orderInfoDialogContext" class="pageFormContent" style="display: none;">
    <fieldset>
        <dl>
            <dt><@label key="orderFormNum.C,colon">订单编号：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="orderStatus.C,colon">订单状态：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="materialCode.C,colon">物料编号：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="materialText.C,colon">物料描述：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="orderQuantity.C,colon">订单数量：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt>未完工数量：</dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt>已排数量：</dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt>未排数量：</dt>
            <dd>
                <input readonly="readonly" class="readonly textInput" type="text">
            </dd>
        </dl>
        <dl>
            <dt><@label key="plannedstartDateTime.C,colon">计划开始时间：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput date" type="text">
                <a class="inputDateButton" href="javascript:;"></a>
            </dd>
        </dl>
        <dl>
            <dt><@label key="plannedendDateTime.C,colon">计划结束时间：</@label></dt>
            <dd>
                <input readonly="readonly" class="readonly textInput date" type="text">
                <a class="inputDateButton" href="javascript:;"></a>
            </dd>
        </dl>
    </fieldset>
    <ul style="float: right; margin: 10px 13px 0px 0px;">
        <li style="float: right;">
            <div class="buttonActive">
                <div class="buttonContent">
                    <button type="button" class="close"><@label key="close.B">关闭</@label></button>
                </div>
            </div>
        </li>
    </ul>
</div>
<!-- 订单计划信息弹出层内容 -->
<div id="orderPlanInfoDialogContext" class="pageFormContent" style="display: none;">
    <form>
        <fieldset>
            <dl>
                <dt><@label key="orderFormNum.C,colon">订单编号：</@label></dt>
                <dd>
                    <input readonly="readonly" class="readonly textInput" type="text">
                </dd>
            </dl>
            <dl>
                <dt><@label key="orderStatus.C,colon">订单状态：</@label></dt>
                <dd>
                    <input readonly="readonly" class="readonly textInput" type="text">
                </dd>
            </dl>
            <dl>
                <dt><@label key="workCenter.C,colon">工作中心：</@label></dt>
                <dd>
                    <select name="workCenterCode" disabled="disabled"></select>
                </dd>
            </dl>
            <dl>
                <dt>计划日期：</dt>
                <dd>
                    <input datefmt="yyyy-MM-dd" name="plannedStartDate" readonly="readonly"    class="readonly textInput date required" type="text">
                    <a class="inputDateButton" href="javascript:;"></a>
                </dd>
            </dl>
            <dl>
                <dt><@label key="plannedQuantity.C,colon">计划数量：</@label></dt>
                <dd>
                    <input min="1" name="plannedQuantity" readonly="readonly" class="readonly textInput number integer required" type="text">
                </dd>
            </dl>
            <dl>
                <dt>计划时长（分）：</dt>
                <dd>
                    <input min="0" max="1440" name="plannedSeconds" readonly="readonly" class="readonly textInput number integer required" type="text">
                </dd>
            </dl>
            <dl>
                <dt><@label key="plannedstartDateTime.C,colon">计划开始时间：</@label></dt>
                <dd>
                    <input dateFmt="yyyy-MM-dd HH:mm:ss" name="plannedstartDateTime" readonly="readonly" class="readonly textInput date" type="text">
                    <a class="inputDateButton" href="javascript:;"></a>
                </dd>
            </dl>
            <dl>
                <dt><@label key="plannedendDateTime.C,colon">计划结束时间：</@label></dt>
                <dd>
                    <input dateFmt="yyyy-MM-dd HH:mm:ss" name="plannedendDateTime" readonly="readonly" class="readonly textInput date" type="text">
                    <a class="inputDateButton" href="javascript:;"></a>
                </dd>
            </dl>
        </fieldset>
        <ul style="float: right; margin: 10px 23px 0px 0px;">
            <li style="float: right; margin-left: 10px;">
                <div class="buttonActiveGrey">
                    <div class="buttonContent">
                        <button type="button" class="close"><@label key="cancel.B">取消</@label></button>
                    </div>
                </div>
            </li>
            <li style="float: right;">
                <div class="buttonActive">
                    <div class="buttonContent">
                        <button type="button" class="submit"><@label key="ok.B">确定</@label></button>
                    </div>
                </div>
            </li>
        </ul>
    </form>
</div>
<script type="text/javascript">
(function($){
    var localData = {
        navTabId: '${navTabId}',
        startDate: '${startDate}',
        endDate: '${endDate}',
        orderType: '${orderType!""}',
        orderNums: '${orderNums}',
        contextPath: '${rc.getContextPath()}'
    },
    localLabels = {
        workCenter: '<@label key="workCenter.C">工作中心</@label>',
        orderArrange: '<@label key="orderArrange.C">订单排产</@label>',
        orderIssue: '<@label key="issued.B">下达</@label>',
        save: '<@label key="save.B">保存</@label>',
        close: '<@label key="close.B">关闭</@label>',
        minute: '<@label key="minute.C">分钟</@label>',
        daysOfWeek: new Array("<@label key='sunday.C'>星期日</@label>", "<@label key='Mon.C'>星期一</@label>", "<@label key='Tues.C'>星期二</@label>", "<@label key='Wed.C'>星期三</@label>",
                "<@label key='Thur.C'>星期四</@label>", "<@label key='Fri.C'>星期五</@label>", "<@label key='Sat.C'>星期六</@label>")
    };
    if (!$.fn.attachValue) {
        $.fn.attachValue = function(index, value) {
            return this.each(function(){
                $('input:eq(' + index + ')', $(this)).val(value);
            });
        };
    }
    if (!$.fn.attachAttr) {
        $.fn.attachAttr = function(index, value) {
            return this.each(function(){
                $('input:eq(' + index + ')', $(this)).attr(value);
            });
        };
    }
    // 局部变量
    var bgpIndex = 0, 
    dateFmt = 'yyyy-MM-dd', 
    dateTimeFmt = 'yyyy-MM-dd HH:mm:ss',
    startDate = localData.startDate.parseDate(dateFmt), 
    calendarDaysMap = {}, 
    workDayPeriodsMap = {},
    capacitiesMap = {},
    allWorkCenters,
    issueData = {},
    endDate = localData.endDate.parseDate(dateFmt),
    perDay = 24 * 60 * 60 * 1000,
    $jGrid = $('#jGridForOrderArrangements', DWZ.context()),
    // grid前三列
    columns = [
        {field: 'workCenterCode', group: 'ids', type: 'checkbox', width: 22},
        {field: 'workcenterCode', text: localLabels.workCenter, width: 100},
        {field: 'productionOrdersView', text: '订单预览', width: 140}
    ],
    // 前三列总宽
    tableWidth = 262,
    // 星期国际化
    daysOfWeek = localLabels.daysOfWeek;
    // 根据开始时间及结束时间追加响应的列，依赖于用户选择的起止日期，最多21天
    for (var int = 0; int < 21; int++) {
        var column = {};
        column.field = startDate.formatDate(dateFmt);
        column.title = startDate.formatDate(dateFmt) + ' ' + daysOfWeek[startDate.getDay()];
        column.text = daysOfWeek[startDate.getDay()];
        column.width = 120;
        column.thrender = function(th){
            th.css({'text-align': 'center'});
        };
        tableWidth += column.width;
        columns.push(column);
        startDate.setTime(startDate.getTime() + perDay);
        if (startDate.getTime() > endDate.getTime()) {
            break;
        }
    }
    // 如果总宽度小于div宽度，则设置为div宽度，列宽自适应
    if (tableWidth < $jGrid.width()) {
        tableWidth = $jGrid.width();
    }
    
    // 页面刷新及数据表查询所需参数
    var postData = {
        navTabId: localData.navTabId,
        orderNums: localData.orderNums,
        startDate: localData.startDate,
        endDate: localData.endDate,
        orderType: localData.orderType
    },
    // 当前页所有ajax回调函数
    ajaxCallback = function(json) {
        if (json.statusCode == DWZ.statusCode.ok) {
            navTab.openTab(localData.navTabId, localData.contextPath + '/manage/productionOrderArrangement/orderArrangement_list_page', 
                    {data: postData, title: localLabels.orderArrange, fresh: true, external: false});
        }
        DWZ.ajaxDone(json);
    };
    
    // 初始化grid
    $jGrid.jGrid({
        layoutH: 83,
        gridHeaderHeight: 51,
        width: tableWidth,
        base: localData.contextPath + '/manage/productionOrderArrangement/',
        autoLoad: false,
        columns: columns,
        lockColumnNum: 3,
        orderable: false,
        pageable: false,
        trselectable: false,
        gridbars: [
            {icon: 'rearrange', text: '重排所选工作中心', title: '无工作日历或产能的工作中心无法排产，确认重排所选工作中心？', 
                target: 'selectedTodo', data: {ids: "{ids}"}, action: function() {
                    // 重排所选
                    arrangeOrder(); 
                }},
            {icon: 'rearrangeAll', text: '重排全部', title: '无工作日历或产能的工作中心无法排产，确认重排全部工作中心？', 
                target: 'confirmTodo', action: function() {
                    // 重排全部
                    arrangeOrder(true); 
                }},
            /*{icon: 'cancelPlan', text: '撤销下达所选订单', title: '如果所选订单分配到其他工作中心，会同时撤销，确定撤销所选？', 
                target: 'selectedTodo', data: {ids: "{ids}"}, action: function() {
                    // 撤销所选操作
                    var selectedOrderNums = getSelectedIssuedOrderNums();
                    if (selectedOrderNums.length == 0) {
                        alertMsg.info('无下达状态的订单！');
                        return false;
                    }
                    $.ajax({
                        url: localData.contextPath + '/manage/productionOrderArrangement/releaseIssuedOrders',
                        type: 'post',
                        data: {
                            orderNums: selectedOrderNums.join(','),
                            navTabId: localData.navTabId
                        },
                        dataType: 'json',
                        cache: false,
                        success: ajaxCallback
                    });
                }},
            {icon: 'cancelPlan', text: '撤销全部', title: '如果所选订单分配到其他工作中心，会同时撤销，确定撤销全部？', 
                target: 'confirmTodo', action: function(){
                    // 撤销全部操作
                    var allOrderNums = getSelectedIssuedOrderNums(true);
                    if (allOrderNums.length == 0) {
                        alertMsg.info('无下达状态的订单！');
                        return false;
                    }
                    $.ajax({
                        url: localData.contextPath + '/manage/productionOrderArrangement/releaseIssuedOrders',
                        type: 'post',
                        data: {
                            orderNums: allOrderNums.join(','),
                            navTabId: localData.navTabId
                        },
                        dataType: 'json',
                        cache: false,
                        success: ajaxCallback
                    });
                }},
            {icon: 'plan', text: localLabels.orderIssue, title: '仅下达当前排产完成的新建订单，未排完的订单仅保存计划数据，确认下达？', 
                target: 'confirmTodo', action: function(){
                    var arrangements = getOrderArrangements();
                    arrangements.startDate = localData.startDate;
                    arrangements.navTabId = localData.navTabId;
                    if (!arrangements.orderPlans || arrangements.orderPlans == '[]') {
                        alertMsg.info('无排产数据！');
                        return false;
                    }
                    // 下达操作
                    $.ajax({
                        url: localData.contextPath + '/manage/productionOrderArrangement/saveOrderPlanListAndIssueOrder',
                        type: 'post',
                        data: arrangements,
                        dataType: 'json',
                        cache: false,
                        success: ajaxCallback
                    });
                }},*/
            {text: '返回', title: '确认返回吗？', type: 'button', render: function($li){
                $li.css({
                    float: 'right',
                    'margin-right': '10px'
                });
                $li.prev('li').css({'border-width': '0px'});
                $('>div', $li).removeClass('buttonActive').addClass('buttonActiveGrey');
            }, target: 'confirmTodo', action: function(){
                navTab.openTab('ORDERARRANGEMENT', localData.contextPath + '/manage/productionOrderArrangement/unarrangedOrder_list_page', {data: {
                    navTabId: localData.navTabId, 
                    startDate: localData.startDate, 
                    endDate: localData.endDate,
                    orderType: localData.orderType
                }, title: localLabels.orderArrange, fresh: true, external: false});
            }},
            {type: 'button', text: localLabels.save, title: '该操作会更新当前页面所有订单的排产计划，是否继续？', 
            target: 'confirmTodo', render: function($li) {
            	$li.css({
                    float: 'right',
                    'margin-right': '10px'
                });
                $li.prev('li').css({'border-width': '0px'});
            }, action: function(){
                var arrangements = getOrderArrangements();
                arrangements.startDate = localData.startDate;
                arrangements.navTabId = localData.navTabId;
                if (!arrangements.orderPlans || arrangements.orderPlans == '[]') {
                    alertMsg.warning('无排产计划数据可保存！');
                    return false;
                }
                // 保存操作
                $.ajax({
                    url: localData.contextPath + '/manage/productionOrderArrangement/saveOrderPlanListAndIssueOrder',
                    type: 'post',
                    data: arrangements,
                    dataType: 'json',
                    cache: false,
                    success: ajaxCallback
                });
            }},
        ]
    });
    
    // 局部使用jQuery选择器上下文
    var $table = $('.gridTbody table', $jGrid), $tbody = $('>tbody', $table), 
    $tr = $('<tr/>'), $thead = $('.gridHeader', $jGrid).height(51).find('thead'),
    trFirst = $('tr:first', $thead);
    
    for (var cIndex = 0; cIndex < columns.length; cIndex++) {
        var column = columns[cIndex];
        if (cIndex < 3) {
            $('th:eq(' + cIndex + ')', trFirst).addClass('bottom-border');
        } else {
            $('<div style="text-align: center;" class="gridCol"/>').append(column.field).appendTo($('th:eq(' + cIndex + ')', trFirst).addClass('bottom-border'));
        }
        $('th:eq(2)', trFirst).css('border-right-color', '#DBE0E3');
    }
    
    // 局部方法
    // 获取background position
    var getBgPosition = function() {
        // 目前77个颜色，使用完后循环
        var pTop = -26 * (bgpIndex % 77);
        bgpIndex++;
        return '0px ' + pTop + 'px';
    },
    // 获取当前选中的工作中心（有序的）
    getSelectedWorkCenters = function() {
        var selectedWorkCenters = new Array();
        $.each($('tr', $tbody), function(){
            var $this = $(this);
            if ($('input[type=checkbox][name=ids]:checked', $this).length > 0) {
                selectedWorkCenters.push($this);
            }
        });
        return selectedWorkCenters;
    },
    // 重排订单 参数为true时重排全部，否则重排所选
    arrangeOrder = function(isAll) {
        // 如果是重排全部，则重排多有行，否则有序选取选中行
        var selectedWorkCenters = isAll ? $('tr', $tbody) : getSelectedWorkCenters();
        arrangeOrders(selectedWorkCenters);
    },
    arrangeOrders = function(selectedWorkCenters) {
        $.each(selectedWorkCenters, function(){
            var $tr = $(this), $orders = $('>td:eq(2) li.order', $tr), workCenterCode = $tr.attr('workCenter');
            // 无默认工作中心的则不排产
            if (workCenterCode == '_blankWorkCenterCode') {
                return true;
            }
            // 删除该工作中心已经排产的计划，更新相关订单数据
            initSelectedWorkCenter($tr);
            // 遍历该工作中心下的订单，进行排产
            $.each($orders, function(){
                var $order = $(this), order = $tbody.data($order.attr('orderNum')), 
                alreadyArrangedQuantity = order.alreadyArrangedQuantity || 0;
                // 获取该工作中心物料产能或标准产能， 如没有产能则无法排产
                var capabilityObj = getCapability(workCenterCode, order.materialCode, order.totalPlannedQuantity);
                if (!capabilityObj) {
                    return true;
                }
                // 产能精确到每秒多少个
                var capability = capabilityObj.standardCapacity * capabilityObj.coefficient / capabilityObj.standardHours / 60 / 60;
                // 遍历该工作中心下没有排满的日期
                $.each($('td[dayTypeCode]:not([arranged])', $tr), function() {
                    var $td = $(this), dateStr = $td.attr('date'), dayTypeCode = $td.attr('dayTypeCode'), 
                    orderPlan = $.extend({}, order), 
                    // 当前日期对应日历的总可排产时长（秒）
                    periodicSeconds = getPeriodicSeconds(workDayPeriodsMap[dayTypeCode]),
                    startTimeObj, endTimeObj;
                    // 当前日期如果已经排产了其他订单，则可排产时长减去相应的时长（剩余可排产时长）
                    if ($('.orderPlan', $td).length > 0) {
                        $.each($('.orderPlan', $td), function(){
                            periodicSeconds -= $(this).data().plannedSeconds;
                        });
                    }
                    // 当前天剩余时间还可排产的数量
                    var dayQuantity = (capability * periodicSeconds).toFixed(0);
                    // 如果订单排完则排下一个订单
					if (order.uncompletedQuantity <= alreadyArrangedQuantity) {
						return false;
					}
					// 如果当日可生产数量为0，则继续排后面的日期
					if (dayQuantity < 1) {
						return true;
					}
                    // 计划日期
                    orderPlan.plannedStartDate = dateStr.parseDate(dateFmt).getTime();
                    // 计划开始时间
                    startTimeObj = getStartTime(workCenterCode, dateStr);
                    if (startTimeObj) {
                        var startDateTimeStr = new Date(dateStr.parseDate(dateFmt).getTime() + perDay * startTimeObj.day).formatDate(dateFmt) 
                            + ' ' 
                            + startTimeObj.time;
                        orderPlan.plannedstartDateTime = startDateTimeStr.parseDate(dateTimeFmt).getTime();
                    }
                    // 当前天可排产的数量大于订单未排产的数量时，则排完
                    if (dayQuantity > order.uncompletedQuantity - alreadyArrangedQuantity) {
                        orderPlan.plannedQuantity = order.uncompletedQuantity - alreadyArrangedQuantity;
                        var seconds = (orderPlan.plannedQuantity / capability).toFixed(0);
                        orderPlan.plannedSeconds = seconds;
                    } else { // 否则按可排数量排
                        orderPlan.plannedQuantity = dayQuantity;
                        orderPlan.plannedSeconds = periodicSeconds;
                        // 当前天剩余可排产时间为0，增加标志
                        $td.attr('arranged', 'arranged');
                    }
                    // 更新已排产数量
                    alreadyArrangedQuantity += parseInt(orderPlan.plannedQuantity);
                    order.alreadyArrangedQuantity = alreadyArrangedQuantity;
                    if (startTimeObj) {
                        // 计划结束时间
                        endTimeObj = getEndTime(workDayPeriodsMap[dayTypeCode], orderPlan.plannedSeconds / 60, startTimeObj);
                        if (endTimeObj) {
                            var endDateTimeStr = new Date(dateStr.parseDate(dateFmt).getTime() + perDay * endTimeObj.day).formatDate(dateFmt) 
                                + ' ' 
                                + endTimeObj.time;
                            orderPlan.plannedendDateTime = endDateTimeStr.parseDate(dateTimeFmt).getTime();
                        }
                    }
                    // 工作中心
                    orderPlan.workCenterCode = workCenterCode;
                    appendOrderPlan($tr, $td, orderPlan);
                });
            });
        });
        updateOrdersArrangedQuantity(selectedWorkCenters);
    },
    // 获取当前下达状态的订单编号，参数为true时所有，否则所选工作中心下
    getSelectedIssuedOrderNums = function(isAll) {
        var selectedWorkCenters = isAll ? $('tr', $tbody) : getSelectedWorkCenters(), orderNums = new Array();
        $.each(selectedWorkCenters, function(){
            var $workcenter = $(this);
            $.each($('.order', $workcenter), function(){
                var $order = $(this), orderNum = $order.attr('orderNum');
                if (orderNums.indexOf(orderNum) >= 0) {
                    return true;
                }
                var order = $tbody.data(orderNum);
                if (order.statuseCode == 2) {
                    orderNums.push(orderNum);
                }
            });
        });
        return orderNums;
    },
    // 获取当前页所有的排产数据，包含计划数据，订单明细数量，所有涉及的订单编号，排产完的订单编号
    getOrderArrangements = function() {
        var orderNums = new Array(), orderPlans = new Array(), 
        orderDetailQuantity = {}, arrangedOrderNums = new Array();
        
        $.each($('.order', $tbody), function(){
            var $order = $(this), orderNum = $order.attr('orderNum');
            if (orderNums.indexOf(orderNum) >= 0) {
                return true;
            }
            var order = $tbody.data(orderNum), isArranged = false;
            order.alreadyArrangedQuantity = order.alreadyArrangedQuantity || 0;
            if (order.alreadyArrangedQuantity >= order.uncompletedQuantity) {
                arrangedOrderNums.push(orderNum);
                isArranged = true;
            }
            orderNums.push(orderNum);
        });
        $.each($('.orderPlan', $tbody), function(){
            var $orderPlan = $(this), orderNum = $(this).attr('orderNum'), orderPlan = $orderPlan.data(), postData = {}, order = $tbody.data(orderNum);
            if (order.alreadyArrangedQuantity >= order.uncompletedQuantity && order.statuseCode == 1) {
                var quantity = 0;
                if (!orderDetailQuantity[orderNum]) {
                    orderDetailQuantity[orderNum] = {};
                }
                if (!orderDetailQuantity[orderNum][orderPlan.workCenterCode]) {
                    orderDetailQuantity[orderNum][orderPlan.workCenterCode] = 0;
                } else {
                    quantity = orderDetailQuantity[orderNum][orderPlan.workCenterCode];
                }
                orderDetailQuantity[orderNum][orderPlan.workCenterCode] = quantity + parseInt(orderPlan.plannedQuantity);
            }
            $.extend(true, postData, orderPlan);
            delete postData.uiDraggable;
            orderPlans.push(postData);
        });
        return {
            orderNums: orderNums.join(','),
            arrangedOrderNums: arrangedOrderNums.join(','),
            orderPlans: JSON.stringify(orderPlans),
            orderDetailQuantity: JSON.stringify(orderDetailQuantity)
        };
    },
    // 根据工作中心及物料获取产能，没有则获取标准产能，都没有则返回null，该工作中心没办法排产
    getCapability = function(workCenterCode, materialCode, plannedQuantity) {
        if (capacitiesMap[workCenterCode]) {
            var standardCapability;
            $.each(capacitiesMap[workCenterCode], function(){
                if (!this.materialCode || this.materialCode == 'null') {
                    standardCapability = this;
                }
                if (this.materialCode == materialCode) {
                    standardCapability = this;
                    return false;
                }
            });
            if (standardCapability) {
                var coefficient = 1;
                if (standardCapability.coefficients) {
                    $.each(standardCapability.coefficients, function(){
                        if (!this.lowerQuantity) {
                            if (plannedQuantity < this.upperQuantity || plannedQuantity == this.upperQuantity) {
                                coefficient = this.coefficient;
                                return false;
                            }
                        } else if (!this.upperQuantity) {
                            if (plannedQuantity > this.lowerQuantity || plannedQuantity == this.lowerQuantity) {
                                coefficient = this.coefficient;
                                return false;
                            }
                        } else if (this.lowerQuantity && this.upperQuantity) {
                            if ((plannedQuantity > this.lowerQuantity && plannedQuantity < this.upperQuantity)
                                    || plannedQuantity == this.lowerQuantity
                                    || plannedQuantity == this.upperQuantity) {
                                coefficient = this.coefficient;
                                return false;
                            }
                        }
                    });
                }
                return {
                    standardCapacity: standardCapability.standardCapacity,
                    standardHours: standardCapability.standardHours,
                    coefficient: coefficient
                };
            }
        }
        return null;
    },
    // 初始化筛选出来的行
    initSelectedWorkCenter = function($tr) {
        var $orders = $('>td:eq(2) li.order', $tr), workCenterCode = $tr.attr('workCenter');
        $.each($orders, function(){
            var $order = $(this), orderNum = $order.attr('orderNum'), orderObj = $tbody.data(orderNum);
            $.each($('.orderPlan[orderNum=' + orderNum + ']', $tr), function() {
                var $orderPlan = $(this), orderPlanObj = $orderPlan.data();
                orderObj.alreadyArrangedQuantity -= parseInt(orderPlanObj.plannedQuantity); // 已排产数量中减掉计划数量
                var $td = $orderPlan.parents('td');
                $orderPlan.removeData().remove(); // 移除计划数据及dom节点
                $td.removeAttr('arranged'); // td移除已排产标记
                updateActualCapability($td);
            });
        });
    },
    // 更新订单排产的数量对应的显示
    updateOrdersArrangedQuantity = function(selectedWorkCenters) {
        $.each(selectedWorkCenters, function(){
            var $tr = $(this), $orders = $('>td:eq(2) li.order', $tr), workCenterCode = $tr.attr('workCenter');
            if (workCenterCode == '_blankWorkCenterCode') { // 没有默认工作中心不处理
                return true;
            }
            $.each($orders, function(){
                updateOrderArrangedQuantity($(this).attr('orderNum'));
            });
        });
    },
    updateOrderArrangedQuantity = function(orderNum) {
        var orderObj = $tbody.data(orderNum), width = (orderObj.uncompletedQuantity - (orderObj.alreadyArrangedQuantity || 0)) * 100 / orderObj.uncompletedQuantity;
        if (width < 0) {
            width = 0
        } else if (width > 100) {
            width = 100
        } else if (width < 50) {
            width = Math.ceil(width);
        } else {
            width = Math.floor(width);
        }
        $('li.order[orderNum=' + orderNum + '] .unarrangedOrder', $tbody).css({
            width: width + '%'
        });
    },
    // 汇总当前日期已经排产的订单数量
    getTotalQuantity = function($td) {
        var totalQuantity = 0;
        $.each($('.orderPlan[orderNum]', $td), function() {
            var $orderPlan = $(this), orderPlanObj = $orderPlan.data();
            totalQuantity += parseInt(orderPlanObj.plannedQuantity);
        });
        return totalQuantity;
    },
    // 追加新的workcenter行
    addRow = function(trObj) {
        if (trObj.workCenterCode != '_blankWorkCenterCode') { 
            $.DWZajax({
                url: localData.contextPath + '/manage/productionOrderArrangement/loadWorkCenterData',
                data: $.extend({}, postData, {workCenterCode: trObj.workCenterCode}),
                async: false,
                callback: function(map){
                    $.extend(true, calendarDaysMap, map.calendarDaysMap);
                    $.extend(true, workDayPeriodsMap, map.workDayPeriodsMap);
                    $.extend(true, capacitiesMap, map.capacitiesMap);
                }
            });
        }
        var tr = $tr.clone().attr({workCenter: trObj.workCenterCode, workCenterTypeCode: trObj.workCenterCode != '_blankWorkCenterCode' ? getWorkCenter(trObj.workCenterCode).workCenterTypeCode : ''}), td = $('<td/>'), tdContent = $('<div class="gridCol" style="height: auto;" />'),
        $sortable = $('<ul class="sortable"/>').addClass('disableSelection'), calendarDaysForWorkcenter = parseCalendarDaysForWorkcenter(trObj.workCenterCode),
        $standardCapability = $('<div class="standard" />'), $actualCapability = $('<div class="actual" />').append('<span class="actualQuantity"/>').append('<span/>').append('<span class="actualHours"/>');
        
        td.clone().append(tdContent.clone().append($('<input name="ids" type="checkbox" />').val(trObj.workCenterCode))).appendTo(tr);
        td.clone().attr('title', trObj.workCenterText).append(tdContent.clone().append(trObj.workCenterText)).appendTo(tr);
        td.clone().droppable({
            hoverClass: "drop-hovered",
            accept: function($drag) {
                if ($drag.is('.order.nonWorkCenter > .order-depict') 
                        && tr.attr('workCenterTypeCode') == $drag.parent().attr('workCenterTypeCode')) {
                    return true;
                }
                return false;
            },
            drop: function(event, ui) {
                var $order = ui.draggable.parent(), data = $tbody.data($order.attr('orderNum'));
                data.workCenterCode = trObj.workCenterCode;
                data.workCenterText = getWorkCenter(data.workCenterCode).workCenterText;
                appendArrangedOrder(data);
                var $parent = $order.parent();
                $order.remove();
                if ($('li.order.nonWorkCenter', $parent).length == 0) {
                    $parent.parents('tr:first').remove();
                    $.jTableTool.initGridColumnWidth($jGrid);
                }
                event.preventDefault();
            }
        }).css('border-right-color', '#DBE0E3').append(tdContent.clone().append($sortable.sortable({
            out: function(event, ui){
                $sortable.sortable("option", "scroll", false);
            },
            over: function(event, ui){
                $sortable.sortable("option", "scroll", true);
            }
        }))).appendTo(tr);
        appendOrder(tr, trObj);
        for (var tIndex = 3; tIndex < columns.length; tIndex++) {
            var $td = td.clone().attr('date', columns[tIndex].field)
            .append($standardCapability.clone())
            .append(tdContent.clone().append($('<ul class="sortable"/>').append('<li/>')))
            .append($actualCapability.clone());
            // td增加日历标记
            if (calendarDaysForWorkcenter) {
                var dayTypeCode = calendarDaysForWorkcenter[columns[tIndex].field];
                if (workDayPeriodsMap[dayTypeCode] && workDayPeriodsMap[dayTypeCode].length > 0) {
                    $td.attr('dayTypeCode', dayTypeCode);
                }
            }
            tr.append($td);
        }
        if (trObj.workCenterCode != '_blankWorkCenterCode') { 
            // 有默认工作中心可以拖放
            tr.appendTo($tbody);
            droppableOrderPlan(tr, trObj);
        } else {
            // 没有默认工作中心则放到第一行
            tr.prependTo($tbody);
        }
        $jGrid.jGrid('lockColumn');
    },
    // 数据追加到已经存在的workcenter行
    appendToRow = function(trObj) {
        var tr = $('tr[workCenter=' + trObj.workCenterCode + ']:first', $tbody);
        appendOrder(tr, trObj);
        $jGrid.jGrid('lockColumn');
    },
    // 追加订单视图
    appendOrder = function($tr, orderObj) {
        // 如果已经存在该订单的视图，返回
        if ($('li[orderNum=' + orderObj.productionOrderNum + ']', $tr).length > 0) {
            return;
        } else {
            var existLi = $('li[orderNum=' + orderObj.productionOrderNum + ']:first', $tbody), backgroundPosition;
            // 如果已经有该订单的视图，复制backgroundPosition， 否则获取新的backgroundPosition
            if (existLi.length == 1) {
                backgroundPosition = existLi[0].style.backgroundPosition;
            } else {
                backgroundPosition = getBgPosition();
            }
            var $order = $('<li class="order"/>').append($('<div class="order-icon" />').addClass('status' + orderObj.statuseCode).attr('title', orderObj.statuseText));
            var $orderTag = $('<div class="order-depict"/>').css({
                backgroundPosition: backgroundPosition
            }).append('<div class="unarrangedOrder"/>').append('<span class="orderNumSpan">' + orderObj.productionOrderNum + '</span>');
            $order.append($orderTag);
            
            if (orderObj.workCenterCode == '_blankWorkCenterCode') {
                $order.addClass('nonWorkCenter');
                $('input[type=checkbox]', $tr).remove();
            } else {
                $order.droppable({
                    hoverClass: "orderPlanRemove",
                    accept: function($orderPlan){
                        // 只接受当前行的计划删除
                        if ($orderPlan.is('tr[workcenter=' + orderObj.workCenterCode + '] .orderPlan[ordernum=' + orderObj.productionOrderNum + ']')) {
                            return true;
                        }
                        return false;
                    },
                    drop: function(event, ui) {
                        deleteProductionOrderPlan(ui.draggable.data(), ui.draggable);
                    }
                });
            }
            
            $order.attr({
                orderNum: orderObj.productionOrderNum,
                workCenterTypeCode: orderObj.workCenterTypeCode
            }).css({backgroundPosition: backgroundPosition}).attr('title', orderObj.materialText);
            $('td:eq(2) ul', $tr).append($order);
            if (!$tbody.data(orderObj.productionOrderNum)) {
                $tbody.data(orderObj.productionOrderNum, orderObj);
            }
        }
    },
    // 追加数据库中已经存在的计划对应的订单视图
    appendArrangedOrder = function(trObj) {
        var tr = $('tr[workCenter=' + trObj.workCenterCode + ']', $tbody), td, plannedStartDate = new Date(trObj.plannedStartDate).formatDate(dateFmt);
        if (tr.length == 0) {
            addRow(trObj);
            tr = $('tr[workCenter=' + trObj.workCenterCode + ']', $tbody);
        } else if (tr.length == 1) {
            appendOrder(tr, trObj);
        }
        td = $('>td[date=' + plannedStartDate +']', tr);
        var existedOrderPlan = td.find('[orderNum=' + trObj.productionOrderNum + ']');
        if (trObj && existedOrderPlan.length == 0) {
            appendOrderPlan(tr, td, trObj);
        } else if (existedOrderPlan.length == 1) {
            plusOrderPlan(existedOrderPlan, trObj);
        }
        updateActualCapability(td);
    },
    // 追加订单计划，包含已排产和新排产
    appendOrderPlan = function($tr, $td, orderPlanObj) {
        var containment, $orderPlan = $('<div class="orderPlan"/>').addClass('disableSelection').css({
            width: orderPlanObj.plannedSeconds * 4 / 60 / 60
        });
        // 非新建状态的只能在当前工作中心拖拽
        //if (orderPlanObj.statuseCode > 1) {
        //    containment = '#jGridForOrderArrangements tbody tr[workCenter=' + orderPlanObj.workCenterCode + ']';
        //} else { // 新建状态的计划可以拖动到任意工作中心
            containment = '#jGridForOrderArrangements tbody';
        //}
        // 订单计划可以拖拽
        $orderPlan.draggable({
            zIndex: 100,
            revert: "invalid",
            appendTo: '#jGridForOrderArrangements .gridScrollerBar',
            containment: containment,
            helper: "clone",
            opacity: 0.6,
            cursor: 'move',
            cursorAt: {left: 1, top: 1},
            scroll: true,
            scrollSpeed: 150,
            drag: function(event, ui) {
                var $gridBody = $('#jGridForOrderArrangements .gridBody');
                if (ui.position.top < 30) {
                    $gridBody.scrollTop($gridBody.scrollTop() - 10);
                } else if (ui.position.top > $gridBody.height()) {
                    $gridBody.scrollTop($gridBody.scrollTop() + 10);
                }
            }
        });
        // 获取对应订单的backgroundPosition， 使计划和订单背景相同
        $orderPlan.data(orderPlanObj).attr('orderNum', orderPlanObj.productionOrderNum)
            .css({backgroundPosition: $('li[orderNum=' + orderPlanObj.productionOrderNum + ']:first', $tr)[0].style.backgroundPosition});
        $('li', $td).append($orderPlan);
        updateOrderArrangedQuantity(orderPlanObj.productionOrderNum);
        updateActualCapability($td);
    },
    // 合并订单计划，更新数据及改变相应的宽度
    plusOrderPlan = function($target, orderPlanObj) {
        var data = $target.data();
        data.plannedQuantity = parseInt(data.plannedQuantity) + parseInt(orderPlanObj.plannedQuantity);
        data.plannedSeconds = parseInt(data.plannedSeconds) + parseInt(orderPlanObj.plannedSeconds);
        data.plannedendDateTime = orderPlanObj.plannedendDateTime;
        $target.css({
            width: data.plannedSeconds * 4 / 60 / 60
        });
        updateActualCapability($target.parents('td'));
        updateOrderArrangedQuantity(orderPlanObj.productionOrderNum);
    },
    // 更新当天实际产量数据
    updateActualCapability = function ($td) {
        if ($('.orderPlan', $td).length == 0) {
            $('.standard, .actual > span', $td).removeClass('greatThanStandard lessThanStandard').text('');
            return;
        }
        var _orderPlan = $('.orderPlan:first', $td).data();
        var capability = getCapability(_orderPlan.workCenterCode, _orderPlan.materialCode, $tbody.data(_orderPlan.productionOrderNum).totalPlannedQuantity);
        var dayTypeCode = $td.attr('dayTypeCode');
        if (!dayTypeCode) {
            $('.standard', $td).text('0/0h');
        } else {
            if (capability) {
                var daySecondes = getPeriodicSeconds(workDayPeriodsMap[dayTypeCode]), standardHours = capability.standardHours * daySecondes / (capability.standardHours * 60 * 60);
                if (parseInt(standardHours) == standardHours) {
                    standardHours = standardHours;
                } else if (parseFloat(standardHours) == standardHours.toFixed(1)) {
                    standardHours = standardHours.toFixed(1);
                } else {
                    standardHours = standardHours.toFixed(2);
                }
                if (standardHours < 0.01) {
                    standardHours = 0.01;
                }
                $('.standard', $td).text((capability.standardCapacity * capability.coefficient * daySecondes / (capability.standardHours * 60 * 60)).toFixed(0) + '/' + standardHours + 'h');
            }
        }
        
        var actualQuantity = 0, actualSeconds = 0;
        $.each($('.orderPlan', $td), function(){
            var orderPlan = $(this).data();
            actualQuantity += parseInt(orderPlan.plannedQuantity);
            actualSeconds += parseInt(orderPlan.plannedSeconds);
        });
        var standard = $('.standard', $td).text().slice(0, -1).split('/'), $actual = $('.actual', $td);
        
        if (parseInt(standard[0]) < actualQuantity) {
            $('.actualQuantity', $actual).removeClass('lessThanStandard').addClass('greatThanStandard').text(actualQuantity);
        } else if (parseInt(standard[0]) > actualQuantity) {
            $('.actualQuantity', $actual).removeClass('greatThanStandard').addClass('lessThanStandard').text(actualQuantity);
        } else {
            $('.actualQuantity', $actual).removeClass('greatThanStandard lessThanStandard').text(actualQuantity);
        }
        
        $('span:eq(1)', $actual).text('/');
        
        var actualHours = actualSeconds / 60 / 60;
        if (parseInt(actualHours) == actualHours) {
            actualHours = actualHours + 'h';
        } else if (parseFloat(actualHours) == actualHours.toFixed(1)) {
            actualHours = actualHours.toFixed(1) + 'h';
        } else {
            actualHours = actualHours.toFixed(2) + 'h';
        }
        if (actualHours == '0.00h') {
            actualHours = '0.01h';
        }
        
        if (standard[1] * 60 * 60 < actualSeconds) {
            $('.actualHours', $actual).removeClass('lessThanStandard').addClass('greatThanStandard').text(actualHours);
        } else if (standard[1] * 60 * 60 > actualSeconds) {
            $('.actualHours', $actual).removeClass('greatThanStandard').addClass('lessThanStandard').text(actualHours);
        } else {
            $('.actualHours', $actual).removeClass('greatThanStandard lessThanStandard').text(actualHours);
        }
        
    },
    // 使相应的td可以放置拖拽的计划
    droppableOrderPlan = function ($tr, trObj) {
        $('>td:nth-child(n+4)', $tr).droppable({
            hoverClass: "drop-hovered",
            accept: function($drag) {
                var $td = $(this);
                // 第一条件，拖拽的元素必须是订单计划
                if ($drag.is('.orderPlan')) {
                    // 其次必须满足工作中心类型相同或者是默认的工作中心其中之一
                    if ($('.order[orderNum=' + $drag.data().productionOrderNum + ']', $tr).length > 0 
                            || $tr.attr('workCenterTypeCode') == getWorkCenter($drag.data().workCenterCode).workCenterTypeCode) {
                        // 滚动条向右滚动后删除计划时，会出现编辑的界面
                        var $delTd = $('td:eq(2)', $tr);
                        if ($td[0].offsetLeft < $delTd[0].offsetLeft + $delTd.width()) {
                            return false;
                        }
                        return true;
                    }
                }
                return false;
            },
            drop: function(event, ui) {
                var data = $.extend({}, ui.draggable.data()), $this = $(this), dayPeriods,
                $tr = $this.parent(), workCenterCode = $tr.attr('workCenter');
                
                // 如果拖拽到自己的td中 不做任何操作
                if ($('.orderPlan[orderNum=' + data.productionOrderNum + ']:first', $this).data() === ui.draggable.data()) {
                    return false;
                }
                var maxMinutes = getMaxMinutes(workCenterCode, $this.attr('date'));
                if (maxMinutes <= 0) {
                    alertMsg.error('该日期最大可排产24小时！');
                    return false;
                }
                data.plannedStartDate = $this.attr('date').parseDate(dateFmt).getTime();
                data.workCenterCode = workCenterCode;
                if ($this.attr('dayTypeCode')) {
                    dayPeriods = workDayPeriodsMap[$this.attr('dayTypeCode')];
                }
                editProductionOrderPlan(data, true, ui.draggable, dayPeriods, maxMinutes);
            }
        });
    },
    // 根据编号获取工作中心信息
    getWorkCenter = function(workCenterCode) {
        var workCenter;
        $.each(allWorkCenters, function(){
            if (this.workCenterCode == workCenterCode) {
                workCenter = this;
                return false;
            }
        });
        return workCenter;
    },
    // 根据工作中心类型以及默认工作中心获取下拉列表
    getWorkCenterOptions = function(workCenterTypeCode, workCenterCode) {
        var options = '', isIncluded = false;
        $.each(allWorkCenters, function(){
            if (this.workCenterTypeCode == workCenterTypeCode) {
                if (this.workCenterCode == workCenterCode) {
                    options += '<option selected="selected" value="' + this.workCenterCode + '">' + this.workCenterText + '</option>';
                    isIncluded = true;
                } else {
                    options += '<option value="' + this.workCenterCode + '">' + this.workCenterText + '</option>';
                }
            }
        });
        if (!isIncluded && workCenterCode) {
            options = '<option selected="selected" value="' + workCenterCode + '">' + getWorkCenter(workCenterCode).workCenterText + '</option>' + options;
        }
        return options;
    },
    isCorrectType = function(workCenterTypeCode, workCenterCode) {
        var isCorrect = false;
        $.each(allWorkCenters, function(){
            if (this.workCenterTypeCode == workCenterTypeCode && this.workCenterCode == workCenterCode) {
                isCorrect = true;
                return false;
            }
        });
        return isCorrect;
    },
    // 填充未完成的订单数据
    fillProductionOrders = function(orders) {
        $.each(orders, function(){
            if (!this.workCenterCode) {
                this.workCenterCode = '_blankWorkCenterCode';
                this.workCenterText = ' ';
            } else if (!isCorrectType(this.workCenterTypeCode, this.workCenterCode)) {
                this.workCenterCode = '_blankWorkCenterCode';
                this.workCenterText = ' ';
            }
            if ($('tr[workCenter=' + this.workCenterCode + '] li.order[orderNum=' + this.productionOrderNum + ']', $tbody).length == 1) {
                return true;
            }
            if ($('tr[workCenter=' + this.workCenterCode + ']:first', $tbody).length == 0) {
                addRow(this);
            } else {
                appendToRow(this);
            }
        });
    },
    // 填充已经存在的订单计划数据，转为图形
    fillArrangedPlans = function(orders) {
        $.each(orders, function(){
            if (!$tbody.data(this.productionOrderNum)) {
                $tbody.data(this.productionOrderNum, this);
            }
            appendArrangedOrder(this);
            if ($tbody.data(this.productionOrderNum).alreadyArrangedQuantity) {
                $tbody.data(this.productionOrderNum).alreadyArrangedQuantity += parseInt(this.plannedQuantity);
            } else {
                $tbody.data(this.productionOrderNum).alreadyArrangedQuantity = parseInt(this.plannedQuantity);
            }
            updateOrderArrangedQuantity(this.productionOrderNum);
        });
    },
    // 查看订单信息
    viewProductionOrder = function(order) {
        $.pdialog.open('', "PrductionOrderView", "订单详情", {height: 260, width: 570, max: false, mask: true, resizable: false, maxable: false, minable: false, callback: function($content){
            $('#orderInfoDialogContext').clone().removeAttr('id').show().appendTo($content);
            $('button.close', $content).on('click', function(e){
                $.pdialog.close($(this).parents('.dialog:first'));
                var event = e || window.event;
                event.preventDefault();
            });
            $('dl', $content).css({width: 270});
            var unarrangedQuantity = order.uncompletedQuantity - (order.alreadyArrangedQuantity || 0);
            unarrangedQuantity = unarrangedQuantity < 0 ? 0 : unarrangedQuantity;
            $content.attachValue(0, order.productionOrderNum)
                .attachValue(1, order.statuseText)
                .attachValue(2, order.materialCode)
                .attachValue(3, order.materialText)
                .attachValue(4, order.totalPlannedQuantity)
                .attachValue(5, order.uncompletedQuantity)
                .attachValue(6, order.alreadyArrangedQuantity || 0)
                .attachValue(7, unarrangedQuantity)
                .attachValue(8, new Date(order.orderPlannedstartDateTime || order.plannedstartDateTime).formatDate(dateTimeFmt))
                .attachValue(9, new Date(order.orderPlannedendDateTime || order.plannedendDateTime).formatDate(dateTimeFmt));
        }});
    },
    // 给默认工作中心不匹配或者没有默认工作中心的订单分配工作中心
    editProductionOrder = function(order, $order) {
        $.pdialog.open('', "PrductionOrderEdit", "分配工作中心", {height: 230, width: 570, max: false, mask: true, resizable: false, maxable: false, minable: false, callback: function($content){
            $('#arrangeOrderWorkCenter').clone().removeAttr('id').show().appendTo($content);
            $('button.close', $content).on('click', function(e){
                $.pdialog.close($(this).parents('.dialog:first'));
                var event = e || window.event;
                event.preventDefault();
            });
            $('dl', $content).css({width: 270});
            $content.attachValue(0, order.productionOrderNum)
                .attachValue(1, order.statuseText)
                .attachValue(2, order.materialCode)
                .attachValue(3, order.materialText)
                .attachValue(4, order.totalPlannedQuantity)
                .attachValue(5, new Date(order.orderPlannedstartDateTime || order.plannedstartDateTime).formatDate(dateTimeFmt))
                .attachValue(6, new Date(order.orderPlannedendDateTime || order.plannedendDateTime).formatDate(dateTimeFmt));
            $('select', $content).append(getWorkCenterOptions(order.workCenterTypeCode)).removeAttr('disabled');
            $('button.submit', $content).on('click', function(e){
                order.workCenterCode = $('select', $content).val();
                order.workCenterText = getWorkCenter(order.workCenterCode).workCenterText;
                appendArrangedOrder(order);
                var $parent = $order.parent();
                $order.remove();
                if ($('li.order', $parent).length == 0) {
                    $parent.parents('tr:first').remove();
                    $.jTableTool.initGridColumnWidth($jGrid);
                }
                $.pdialog.close($(this).parents('.dialog:first'));
                var event = e || window.event;
                event.preventDefault();
            });
        }});
    },
    // 创建订单计划dialog
    createOrderPlanDialog = function(title, dialogId, orderPlan, fillCallBack) {
        $.pdialog.open('', dialogId, title, {height: 230, width: 590, max: false, mask: true, resizable: false, maxable: false, minable: false, callback: function($content){
            var minDate = new Date(orderPlan.plannedStartDate).formatDate(dateFmt), 
            maxDate = new Date(parseInt(orderPlan.plannedStartDate) + 24 * 60 * 60 * 1000).formatDate(dateFmt);
            
            $('#orderPlanInfoDialogContext').clone().removeAttr('id').show().appendTo($content);
            $('select', $content).empty().append(getWorkCenterOptions(orderPlan.workCenterTypeCode, orderPlan.workCenterCode));
            $('dl', $content).css({width: 280});
            $content.attachValue(0, orderPlan.productionOrderNum)
            .attachValue(1, orderPlan.statuseText)
            .attachValue(2, new Date(orderPlan.plannedStartDate).formatDate(dateFmt))
            .attachAttr(2, {
                minDate: localData.startDate,
                maxDate: localData.endDate
            })
            .attachValue(3, orderPlan.plannedQuantity)
            .attachAttr(3, {
                originalValue: orderPlan.plannedQuantity
            })
            .attachValue(4, (parseInt(orderPlan.plannedSeconds / 60) == orderPlan.plannedSeconds / 60) ? orderPlan.plannedSeconds / 60 : (orderPlan.plannedSeconds / 60).toFixed(2))
            .attachValue(5, !orderPlan.plannedstartDateTime ? '' : new Date(orderPlan.plannedstartDateTime).formatDate(dateTimeFmt))
            .attachAttr(5, {
                minDate: minDate,
                maxDate: maxDate
            })
            .attachValue(6, !orderPlan.plannedendDateTime ? '' : new Date(orderPlan.plannedendDateTime).formatDate(dateTimeFmt))
            .attachAttr(6, {
                minDate: minDate,
                maxDate: maxDate
            });
            
            if ($.isFunction(fillCallBack)) {
                var $dialog = $content.parents('.dialog:first');
                $('button.close', $content).on('click', function(e){
                    $.pdialog.close($dialog);
                    var event = e || window.event;
                    event.preventDefault();
                });
                fillCallBack($dialog);
            } else {
                $('button.close', $content).parents('li:first').remove();
                $('button.submit', $content).on('click', function(e){
                    $.pdialog.close($(this).parents('.dialog:first'));
                    var event = e || window.event;
                    event.preventDefault();
                }).text(localLables.close);
            }
        }});
    },
    // 比较计划日期是否更改
    compareDate = function() {
        return new Date(arguments[0]).formatDate(dateFmt) == new Date(arguments[1]).formatDate(dateFmt)
    },
    // 编辑计划
    editProductionOrderPlan = function(orderPlan, isDragged, $source, dayPeriods, maxMinutes) {
        createOrderPlanDialog('编辑订单计划', 'PrductionOrderPlanEdit', orderPlan, function($dialog) {
            var $content = $('.pageFormContent:first', $dialog), $form = $('form', $content)/*.addClass('required-validate')*/, 
            $fieldset = $('fieldset', $content), $plannedQuantityInput = $('[name=plannedQuantity]', $fieldset),
            $dateInput = $('input[name=plannedStartDate]', $fieldset), $plannedSecondsInput = $('[name=plannedSeconds]', $fieldset),
            $timesInput = $('input[name=plannedstartDateTime], input[name=plannedendDateTime]', $fieldset).removeClass('readonly'),  $slect = $('select', $fieldset),
            $startTimeInput = $('input[name=plannedstartDateTime]', $fieldset), $endTimeInput = $('input[name=plannedendDateTime]', $fieldset);
            
            if (isDragged) {
                $('input:eq(3)', $fieldset).removeClass('readonly').removeAttr('readonly');
            } else {
                $('input:gt(2):not(.date)', $fieldset).removeAttr('readonly');
                $('input:gt(1)', $fieldset).removeClass('readonly');
                //if (orderPlan.statuseCode == 1) {
                    $slect.removeAttr('disabled');
                //}
            }
            
            if (!maxMinutes) {
                maxMinutes = getMaxMinutes(orderPlan.workCenterCode, $dateInput.val(), $source);
            }
            $plannedSecondsInput.attr('max', maxMinutes);
            
            var orderObj = $tbody.data(orderPlan.productionOrderNum),
            maxQuantity = orderObj.uncompletedQuantity - (orderObj.alreadyArrangedQuantity || 0) + parseInt(orderPlan.plannedQuantity);
            $plannedQuantityInput.attr('max', maxQuantity).attr('title', '最大数量' + maxQuantity);
            
            $plannedSecondsInput.parent().on('mouseenter', '.error, input', function(){
                $(this).attr('title', '该工作中心当天还可排产' + maxMinutes + localLabels.minute);
            });
            
            $slect.on('change', function(){
                if ($dateInput.val()) {
                    maxMinutes = getMaxMinutes($slect.val(), $dateInput.val(), $source);
                    $plannedSecondsInput.attr('max', maxMinutes);
                }
                if (this.value != $source.parents('tr:first').attr('workCenter')) {
                    $plannedQuantityInput.attr('max', $plannedQuantityInput.attr('originalValue')).attr('title', '最大数量' + $plannedQuantityInput.attr('originalValue'));
                } else {
                    $plannedQuantityInput.attr('max', maxQuantity).attr('title', '最大数量' + maxQuantity);
                }
            });
            
            $dateInput.on('change', function(){
                var dateValue = $(this).val(), startTime = $startTimeInput.val(), endTime = $endTimeInput.val();
                if (dateValue) {
                    maxMinutes = getMaxMinutes($slect.val(), dateValue, $source);
                    $plannedSecondsInput.attr('max', maxMinutes);
                    var maxDate = new Date(dateValue.parseDate(dateFmt).getTime() + 24 * 60 * 60 * 1000).formatDate(dateFmt);
                    $timesInput.attr({
                        minDate: dateValue,
                        maxDate: maxDate
                    });
                    if (startTime) {
                        //$startTimeInput.val(dateValue + startTime.substring(dateValue.length));
                        $startTimeInput.val('');
                    }
                    if (endTime) {
                        //$endTimeInput.val(dateValue + endTime.substring(dateValue.length));
                        $endTimeInput.val('')
                    }
                }
            });
            var cDate = $dateInput.val();
            
            var autocompleteTimeInput = function(seconds) {
                var startTime = $startTimeInput.val();
                if (seconds) {
                    if (startTime) {
                        var endTimeObj = getEndTime(dayPeriods, seconds, {day: 0, time: startTime.substring(cDate.length + 1)});
                        if (endTimeObj.day > 0) {
                            cDate = new Date(startTime.parseDate(dateTimeFmt).getTime() + 24 * 60 * 60 * 1000).formatDate(dateFmt);
                        }
                        $endTimeInput.val(cDate + ' ' + endTimeObj.time);
                    } else {
                        $endTimeInput.val('');
                    }
                }
            };
            
            $plannedSecondsInput.on('keyup', function() {
                var seconds = $(this).val();
                autocompleteTimeInput(seconds);
            });
            
            $('select, input[name=plannedStartDate]', $fieldset).on('change', function() {
                var startTimeObj = getStartTime($slect.val(), $dateInput.val());
                if (startTimeObj) {
                    $startTimeInput.val(cDate + ' ' + startTimeObj.time);
                    $plannedSecondsInput.trigger('keyup');
                } else {
                    $startTimeInput.val('');
                    $endTimeInput.val('');
                }
            });
            
            if (isDragged) {
                $plannedQuantityInput.attr({max: orderPlan.plannedQuantity});
                $dateInput.attr('disabled', true).removeClass('required');
                var startTimeObj = getStartTime($slect.val(), $dateInput.val());
                if (startTimeObj) {
                    $startTimeInput.val(cDate + ' ' + startTimeObj.time);
                } else {
                    $startTimeInput.val('');
                }
                $plannedSecondsInput.trigger('keyup');
                $plannedQuantityInput.on('keyup', function(){
                    var value = $(this).val();
                    if (value && parseInt(value)) {
                        var coefficient = value / orderPlan.plannedQuantity,
                        detachSeconds = (orderPlan.plannedSeconds * coefficient).toFixed(0);
                        $plannedSecondsInput.attr('seconds', detachSeconds).val(parseInt(detachSeconds / 60) == detachSeconds / 60 ? detachSeconds / 60 : (detachSeconds / 60).toFixed(2)).trigger('keyup');
                    }
                });
                $plannedQuantityInput.attr('max', $plannedQuantityInput.attr('originalValue')).attr('title', '最大数量' + $plannedQuantityInput.attr('originalValue'));
            }
            
            $timesInput.removeClass('readonly');
            $plannedQuantityInput.removeAttr('readonly').removeClass('readonly').addClass('required');
            
            $('button.submit', $content).on('click', function(e){
                if (!$form.valid()) {
                    return false;
                }
                var temObj = {};
                $.each($('[name]', $fieldset), function(){
                    temObj[$(this).attr('name')] = this.value;
                });
                $('[name=workCenterCode]', $fieldset).removeAttr('disabled');
                temObj.workCenterText = $('select[name=workCenterCode]>option[value=' + temObj.workCenterCode + ']', $fieldset).text();
                temObj.plannedStartDate = temObj.plannedStartDate.parseDate(dateFmt).getTime();
                if (temObj.plannedstartDateTime != '') {
                    temObj.plannedstartDateTime = temObj.plannedstartDateTime.parseDate(dateTimeFmt).getTime();
                } else {
                    temObj.plannedstartDateTime = null;
                }
                if (temObj.plannedendDateTime != '') {
                    temObj.plannedendDateTime = temObj.plannedendDateTime.parseDate(dateTimeFmt).getTime();
                } else {
                    temObj.plannedendDateTime = null;
                }
                temObj.plannedSeconds = (temObj.plannedSeconds * 60).toFixed(0);
                
                var orderPlanCopy = $.extend({}, orderPlan), newObj = $.extend(true, orderPlanCopy, temObj);
                // 如果不是拖拽，工作中心及日期不变则更新
                if (!isDragged && orderPlan.workCenterCode == temObj.workCenterCode 
                        && compareDate(temObj.plannedStartDate, orderPlan.plannedStartDate)) {
                    updateProductionOrderPlan($source, newObj, orderPlan.plannedQuantity);
                } else {
                    // 如果数量相等，需要删除原来的排产
                    var oldQuantity = parseInt(orderPlan.plannedQuantity), newQuantity = parseInt(temObj.plannedQuantity),
                    $td = $source.parents('td');
                    if (oldQuantity == newQuantity) {
                        $source.removeData().remove();
                    } else if (oldQuantity > newQuantity) {
                        $source.data().plannedQuantity = oldQuantity - newQuantity;
                        $source.data().plannedSeconds = orderPlan.plannedSeconds - temObj.plannedSeconds;
                        $source.css({
                            width: $source.data().plannedSeconds * 4 / 60 / 60
                        });
                    } else {
                        return false;
                    }
                    if ($('.orderPlan', $td).length == 0) {
                        $td.removeAttr('arranged');
                    }
                    appendArrangedOrder(newObj);
                    updateActualCapability($td);
                }
                $.pdialog.close($dialog);
                var event = e || window.event;
                event.preventDefault();
            });
            
            $('[name]', $fieldset).on('keydown', function(e){
                var event = e || window.event;
                if (event.keyCode == 13) {
                    $('button.submit', $content).click();
                    event.preventDefault();
                }
            });
            
            $content.initUI();
        });
    },
    // 更新订单计划数据及图形
    updateProductionOrderPlan = function($orderPlan, orderPlan, originalQuantity) {
        $tbody.data($orderPlan.attr('orderNum')).alreadyArrangedQuantity += parseInt(orderPlan.plannedQuantity) - parseInt(originalQuantity);
        $orderPlan.data(orderPlan);
        $orderPlan.css({
            width: orderPlan.plannedSeconds * 4 / 60 / 60
        });
        updateOrderArrangedQuantity(orderPlan.productionOrderNum);
        updateActualCapability($orderPlan.parents('td'));
    },
    // 查看订单计划
    viewProductionOrderPlan = function(orderPlan) {
        createOrderPlanDialog('订单计划详情', 'PrductionOrderPlanView', orderPlan);
    },
    // 删除订单计划
    deleteProductionOrderPlan = function(orderPlan, $orderPlan) {
        var _doDelete = function() {
            $tbody.data($orderPlan.attr('orderNum')).alreadyArrangedQuantity -= parseInt($orderPlan.data().plannedQuantity);
            var $td = $orderPlan.parents('td');
            $td.removeAttr('arranged').end().removeData().remove();
            updateOrderArrangedQuantity(orderPlan.productionOrderNum);
            updateActualCapability($td);
        };
        alertMsg.confirm('确定要删除该计划吗？', {okCall: _doDelete});
    },
    // 获取工作中心该时间段的日历数据
    parseCalendarDaysForWorkcenter = function(workcenterCode) {
        if (calendarDaysMap[workcenterCode]) {
            var calendarDaysForWorkcenter = {};
            $.each(calendarDaysMap[workcenterCode], function(){
                calendarDaysForWorkcenter[new Date(this.calendarDate).formatDate(dateFmt)] = this.dayTypeCode;
            });
            return calendarDaysForWorkcenter;
        } else {
            return null;
        }
    },
    // 获取当前日期最多还可排产的时长，一天一共做多24小时
    getMaxMinutes = function (workCenterCode, plannedStartDate, $source) {
        var $td = $('tr[workCenter=' + workCenterCode + '] > td[date=' + plannedStartDate + ']', $tbody),
        maxMinutes = 1440; // 24h
        var totalSeconds = 0;
        if ($td.length == 1) {
            $.each($('.orderPlan', $td), function() {
                if ($source) {
                    if ($source.data() !== $(this).data()) {
                        totalSeconds += parseInt($(this).data().plannedSeconds);
                    }
                } else {
                    totalSeconds += parseInt($(this).data().plannedSeconds);
                }
            });
        }
        return maxMinutes - Math.ceil(totalSeconds / 60);
    },
    // 获取工作中心指定日期的日历开始时间，如果没有则返回null
    getStartTime = function(workCenterCode, plannedStartDate) {
        var $td = $('tr[workCenter=' + workCenterCode + '] >td[date=' + plannedStartDate + ']', $tbody);
        if ($td.length == 1) {
            $orderPlan = $('li .orderPlan:last', $td);
            if ($orderPlan.length == 1) {
                var startStr = new Date($orderPlan.data().plannedendDateTime).formatDate(dateTimeFmt);
                if (startStr.substring(0, plannedStartDate.length) == plannedStartDate) {
                    return {
                        day: 0,
                        time: startStr.substring(plannedStartDate.length + 1)
                    };
                }
                return {
                    day: 1,
                    time: startStr.substring(plannedStartDate.length + 1)
                };
            }
        }
        var calendarDays = parseCalendarDaysForWorkcenter(workCenterCode);
        if (calendarDays) {
            var dayTypeCode  = calendarDays[plannedStartDate];
            if (dayTypeCode && workDayPeriodsMap[dayTypeCode] && workDayPeriodsMap[dayTypeCode].length > 0) {
                return transformSecondsToTime(parseTimeToNumber(workDayPeriodsMap[dayTypeCode][0].startTime, false));
            }
        }
        return null;
    },
    // 获取指定日历的工作时长（秒）
    getPeriodicSeconds = function(dayPeriods) {
        var seconds = 0;
        $.each(dayPeriods, function(){
            if (this.startTime && this.endTime) {
                startSeconds = parseTimeToNumber(this.startTime, this.nextDayFlag == 1);
                endSeconds = parseTimeToNumber(this.endTime, this.nextDayFlag == 1 || this.spanDaysFlag == 1);
                seconds += (endSeconds - startSeconds);
            }
        });
        return seconds;
    },
    // 根据排产时长、排产开始时间及日历信息获取排产结束时间
    getEndTime = function(dayPeriods, minutes, startTimeObj) {
        var startSeconds = 0, endSeconds = 0, seconds = Math.ceil(minutes * 60), endTimeObj, startTimeSeconds = 0;
        if (dayPeriods) {
            if (startTimeObj.time) {
                startTimeSeconds = parseTimeToNumber(startTimeObj.time, startTimeObj.day == 1);
            }
            $.each(dayPeriods, function(){
                if (this.startTime && this.endTime) {
                    startSeconds = parseTimeToNumber(this.startTime, this.nextDayFlag == 1);
                    endSeconds = parseTimeToNumber(this.endTime, this.nextDayFlag == 1 || this.spanDaysFlag == 1);
                    if (startTimeSeconds > startSeconds) {
                        if (startTimeSeconds > endSeconds) {
                            return true;
                        }
                        startSeconds = startTimeSeconds;
                    }
                    if (startSeconds + seconds < endSeconds) {
                        endTimeObj = transformSecondsToTime(startSeconds + seconds);
                        return false;
                    } else {
                        seconds = seconds - (endSeconds - startSeconds);
                    }
                }
            });
            if (!endTimeObj) {
                endTimeObj = transformSecondsToTime(endSeconds);
            }
            return endTimeObj;
        } else {
            startTimeSeconds = parseTimeToNumber(startTimeObj.time, startTimeObj.day == 1);
            return transformSecondsToTime(startTimeSeconds + seconds);
        }
        return null;
    },
    // 将时间字符串转换为秒
    parseTimeToNumber = function(timeStr, isNextDay) {
        var timeArr = timeStr.trim().split(':'),
        seconds = parseInt(detachZero(timeArr[0] || 0)) * 60 * 60 + parseInt(detachZero(timeArr[1] || 0)) * 60 + parseInt(detachZero(timeArr[2] || 0));
        if (isNextDay) {
            seconds += 24 * 60 * 60;
        }
        return seconds;
    },
    // 将秒转换为时间字符串
    transformSecondsToTime = function(seconds) {
        var hours = Math.floor(seconds / (60 * 60)),
        minutes = Math.floor((seconds % (60 * 60)) / 60),
        seconds = (seconds % (60 * 60)) % 60;
        return {
            day: Math.floor(hours / 24),
            time: patchTime(hours % 24) + ':' + patchTime(minutes) + ':' + patchTime(seconds)
        };
    },
    // 去掉时间字符串中开始的0
    detachZero = function(t) {
        if (t.length == 2 && t.indexOf('0') == 0) {
            return t.substring(1);
        }
        return t;
    },
    // 给10以下的时间前补0
    patchTime = function(t) {
        if (t < 10) {
            t = '0' + t;
        }
        return t;
    },
    // 加载工作中心相关数据，包括日历信息以及产能信息
    loadWorkCenters = function(callback) {
        $.DWZajax({
            url: localData.contextPath + '/manage/productionOrderArrangement/loadWorkCenters',
            callback: function(workCenters){
                allWorkCenters = workCenters;
                callback();
            }
        });
    },
    loadOrderPlansAndOrder = function() {
        $.DWZajax({
            url: localData.contextPath + '/manage/productionOrderArrangement/getUncompletedOrdersByOrderNums',
            data: postData,
            callback: function(data){
                $tbody.empty().detach();
                fillArrangedPlans(data.orderPlans);
                fillProductionOrders(data.arrangedOrders);
                fillProductionOrders(data.uncompletedOrders);
                $tbody.appendTo($table);
                $.jTableTool.initGridColumnWidth($jGrid);
                
                $('tbody > tr:first li.order.nonWorkCenter > .order-depict', $jGrid).draggable({
                    zIndex: 200,
                    revert: "invalid",
                    appendTo: '#jGridForOrderArrangements .gridScrollerBar',
                    opacity: 0.6,
                    helper: "clone",
                    cursor: 'move',
                    cursorAt: {left: 1, top: 1},
                    scroll: true,
                    scrollSpeed: 150,
                    drag: function(event, ui) {
                        var $gridBody = $('#jGridForOrderArrangements .gridBody');
                        if (ui.position.top < 30) {
                            $gridBody.scrollTop($gridBody.scrollTop() - 10);
                        } else if (ui.position.top > $gridBody.height()) {
                            $gridBody.scrollTop($gridBody.scrollTop() + 10);
                        }
                    }
                });
            }
        });
    };
    // 页面渲染完后，绑定响应的时间到tbody上
    $(function(){
        $tbody.on('dblclick', '.order, .orderPlan', function() {
            var $this = $(this), isOrder = $this.is('.order'), isOrderPlan = $this.is('.orderPlan');
            if (isOrder) {
                if ($this.is('.nonWorkCenter')) {
                    editProductionOrder($tbody.data($this.attr('orderNum')), $this);
                    return;
                }
                viewProductionOrder($tbody.data($this.attr('orderNum')));
            } else if (isOrderPlan) {
                if ($this.is('.disabled')) {
                    viewProductionOrderPlan($this.data());
                } else {
                    var dayPeriods, dayTypeCode = $this.parents('td:first').attr('dayTypeCode');
                    if (dayTypeCode) {
                        dayPeriods = workDayPeriodsMap[dayTypeCode];
                    }
                    editProductionOrderPlan($this.data(), false, $this, dayPeriods);
                }
            }
        });
        
        $tbody.on('mouseenter', '.order, .orderPlan', function(){
            var $this = $(this), isOrder = $this.is('.order'), isOrderPlan = $this.is('.orderPlan'),
            getPosition = function() {
            	var left = $this.position().left + $this.width();
            	if (left + 17 > $this.parent().width()) {
            		left = $this.position().left - 16;
            	}
	            return	{
	                left: left,
	                top: $this.position().top + 10
	            };
            };
            if (isOrder) {
                if ($this.is('.nonWorkCenter')) {
                    var editBtn = $('<a class="editOrder" title="分配工作中心" />');
                    if ($this.find('>a.editOrder').length == 0) {
                        $this.append(editBtn.on('click', function(){
                            editProductionOrder($tbody.data($this.attr('orderNum')), $this);
                        }));
                    } else {
                        $this.find('>a.editOrder').show();
                    }
                    return;
                }
                var viewBtn = $('<a class="viewOrder" title="订单详情" />');
                if ($this.find('>a.viewOrder').length == 0) {
                    $this.append(viewBtn.on('click', function(){
                        viewProductionOrder($tbody.data($this.attr('orderNum')));
                    }));
                } else {
                    $this.find('>a.viewOrder').show();
                }
            } else if (isOrderPlan) {
                var viewBtn = $('<a class="viewOrderPlan" title="计划详情" />'), editBtn = $('<a class="editOrderPlan" title="编辑计划" />');
                if ($this.is('.disabled')) {
                    if ($this.prevAll('a.viewOrderPlan').length == 0) {
                        viewBtn.on('mouseleave', function(){
                            $(this).off('click').hide();
                        }).css(getPosition()).on('click', function(){
                            viewProductionOrderPlan($this.data());
                        }).prependTo($this.parent());
                    } else {
                        $this.prevAll('a.viewOrderPlan:first').css(getPosition()).off('click').on('click', function() {
                            viewProductionOrderPlan($this.data());
                        }).show();
                    }
                } else {
                    if ($this.prevAll('a.editOrderPlan').length == 0) {
                        editBtn.on('mouseleave', function(){
                            $(this).off('click').hide();
                        }).css(getPosition()).on('click', function(){
                            var dayPeriods, dayTypeCode = $this.parents('td:first').attr('dayTypeCode');
                            if (dayTypeCode) {
                                dayPeriods = workDayPeriodsMap[dayTypeCode];
                            }
                            editProductionOrderPlan($this.data(), false, $this, dayPeriods);
                        }).prependTo($this.parent());
                    } else {
                        $this.prevAll('a.editOrderPlan:first').css(getPosition()).off('click').on('click', function() {
                            var dayPeriods, dayTypeCode = $this.parents('td:first').attr('dayTypeCode');
                            if (dayTypeCode) {
                                dayPeriods = workDayPeriodsMap[dayTypeCode];
                            }
                            editProductionOrderPlan($this.data(), false, $this, dayPeriods);
                        }).show();
                    }
                }
            }
        });
        
        $tbody.on('mouseleave', '.order, .orderPlan', function(){
            var $this = $(this), isOrder = $this.is('.order'), isOrderPlan = $this.is('.orderPlan');
            if (isOrder) {
                $(this).find('>a.viewOrder, >a.editOrder').hide();
            } else if (isOrderPlan) {
                var $this = $(this);
                setTimeout(function() {
                    $.each($this.prevAll('a.viewOrderPlan, a.editOrderPlan'), function(){
                        if ($(this).is(':hover')) {
                            return;
                        } else {
                            $(this).off('click').hide();
                        }
                    });
                }, 20);
            }
        });
        
        setTimeout(function(){
            loadWorkCenters(loadOrderPlansAndOrder);
        }, 50);
    });
})(jQuery);
</script>
